﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ExcelFileQueryTool
{
    public partial class frmCreateClientFile : Form
    {
        public string ClientFile { get; private set; }
        private string _salesYear;

        public frmCreateClientFile(string clientName, string type = null, string person = null, string phone = null, string addr = null, string salesYear = null)
        {
            InitializeComponent();

            cboxType.Items.AddRange(AppConfig.ClientTypes);

            if (AppConfig.ClientTypes.Contains(type) == false)
                type = null;

            _salesYear = salesYear;

            cboxType.SelectedItem = type ?? cboxType.Items[0].ToString();
            txtName.Text = clientName;
            txtContactPerson.Text = person;
            txtPhone.Text = phone;
            txtAddress.Text = addr;
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            var client_type = cboxType.SelectedItem.ToString();
            var file = Path.Combine(AppConfig.SourceFolder, client_type, string.Format("[对数表]{0}.xlsx", txtName.Text.Trim()));
            if (File.Exists(file))
                throw new Exception("创建客户文件失败，文件已存在：" + file);

            this.ClientFile = file;

            var name = txtName.Text.Trim();
            var person = txtContactPerson.Text.Trim().PadRight(16);
            var phone = txtPhone.Text.Trim().PadRight(20);
            var addr = txtAddress.Text.Trim();

            using (ExcelPackage package = new ExcelPackage(new FileInfo(AppConfig.ClientFileTpl)))
            {
                if (chkMultiSheets.Checked == false)
                    package.Workbook.Worksheets.Delete("交易汇总");

                foreach (var sheet in package.Workbook.Worksheets.Where(x => x.IsDataSheet()))
                {
                    if (sheet.HeaderFooter.OddHeader.CenteredText.Contains("x交易"))
                        sheet.HeaderFooter.OddHeader.CenteredText = sheet.HeaderFooter.OddHeader.CenteredText.Replace("x交易", name + "交易");
                    else
                        sheet.HeaderFooter.OddHeader.CenteredText = sheet.HeaderFooter.OddHeader.CenteredText.Replace("交易", name + "交易");

                    var contactInfo = string.Format(AppConfig.ClientFileContactInfoFormat, person, phone, addr);
                    sheet.HeaderFooter.OddHeader.LeftAlignedText = Regex.Replace(sheet.HeaderFooter.OddHeader.LeftAlignedText, AppConfig.ClientFileContactInfoRegexPattern, contactInfo); ;
                }

                package.Workbook.Worksheets["材料"].Cells[2, 1].Value = (_salesYear ?? DateTime.Now.Year.ToString()) + "年";
                package.Workbook.Worksheets["参数"].Hidden = eWorkSheetHidden.Hidden;

                package.SaveAs(new FileInfo(file));
            }

            if (chkSyncToDB.Checked)
            {
                var crm_people = new CRMPeople
                {
                    Address = addr,
                    CreatedTime = DateTime.Now,
                    Gender = "男",
                    IndexCode = StringHelper.ChinessWordToPinYin(name),
                    LastUpdatedTime = DateTime.Now,
                    Name = name,
                    Status = (short)DBRecordStatus.Normal,
                    Telephone = phone,
                    TypeCode = client_type
                };

                CrmPeopleService svc = new CrmPeopleService(AppConfig.DBConnectionString);
                var crm_people_db = svc.GetByName(name);

                if (crm_people_db == null)
                {
                    svc.Add(crm_people);
                }
                else
                {
                    crm_people.Id = crm_people_db.Id;
                    crm_people.LastUpdatedTime = DateTime.Now;
                    crm_people.NickName = crm_people_db.NickName;
                    crm_people.Note = crm_people_db.Note;
                    svc.Update(crm_people);
                }
            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void lblContactPerson_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtContactPerson.Text = txtName.Text;
        }
    }
}